<?php

class LaboratorioModel extends Database {
    
    const TABLE = "laboratorio";
    
    const ID = "id";
    const NOME = "nome";
    const TELEFONE = "telefone";
    const CNPJ = "cnpj";
    
    public function insert(Laboratorio $laboratorio) {
        $values = get_object_vars($laboratorio);
        unset($values["id"]);
        $fields = implode(",", array(self::NOME, self::TELEFONE, self::CNPJ));
        return parent::insert(self::TABLE, $fields, Database::turnInValues($values));
    }
    
    public function select($fields = " * ", $condition = null, $limit = null) {
        if(is_array($fields)) $fields = implode(",", $fields);
        $res = parent::select(self::TABLE, $fields, $condition, $limit);
        $ana = $this->getAnnalisses();
        $laboratorios = array();
        while(($row = $ana->fetchObject($res)) !== false){
            $laboratorios[] = new Laboratorio(isset($row->{ self::ID })? $row->{ self::ID } : 0,
                                isset($row->{ self::NOME })? ($row->{ self::NOME }) : "",
                                isset($row->{ self::TELEFONE })? $row->{ self::TELEFONE } : "",
                                isset($row->{ self::CNPJ })? $row->{ self::CNPJ } : "" 
                                );
        }
        return $laboratorios;
    }
    
    public function update(Laboratorio $laboratorio) {
        $dic = array(
            self::NOME => $laboratorio->nome,
            self::TELEFONE => $laboratorio->telefone,
            self::CNPJ => $laboratorio->cnpj
        );
        $condition = self::ID." = ".$laboratorio->id;
        return parent::formattedUpdates(self::TABLE, Database::turnInUpdateValues($dic), $condition);
    }
    
    public function delete($id_laboratorio){
        $condition = self::ID." = $id_laboratorio";
        return parent::delete(self::TABLE, $condition);
    }
    
    public function handleError() {
        $err_code = $this->errorCode(); 
        if($err_code == Annalisses::ERR_DUPLICATE) 
            return "Já existe um laboratório com este nome ou CNPJ";
        return parent::handleError();
    }
}

?>
